package com.jiutong.meipengdai.ui.activitys;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;

import com.gyf.barlibrary.ImmersionBar;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.entity.CheckVersionRespond;
import com.jiutong.meipengdai.entity.CityListRespon;
import com.jiutong.meipengdai.http.model.interfaces.CheckVersionBiz;
import com.jiutong.meipengdai.http.model.requests.CommonRequest;
import com.jiutong.meipengdai.http.model.requests.UserInfoRequest;
import com.jiutong.meipengdai.http.present.CheckVersionPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.installapk.DownLoadService;
import com.jiutong.meipengdai.ui.fragments.HomeFragment;
import com.jiutong.meipengdai.ui.fragments.LoanFragment2v;
import com.jiutong.meipengdai.ui.fragments.PersonalCenterFragment;
import com.jiutong.meipengdai.utils.IOUtil;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.views.dialog.BaseDialog;
import com.orhanobut.logger.Logger;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements View.OnClickListener, CheckVersionBiz {

    public static final String KEY_MESSAGE = "message";
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isForeground = false;
    private Fragment mContent;
    private LoanFragment2v loanFragment;
    private HomeFragment homeFragment;
    private View rb_home;
    private View rb_loan;
    private View rb_person;
    private PersonalCenterFragment personFragment;
    private long currentTime;
    private boolean isExit = false;
    private CheckVersionPresent checkVersionPresent;
    private BaseDialog updateDialog;
    private String registrationID;
    private UserInfoRequest request;
    private SubscriberOnNextListener onNextListener;
    private HashMap fieldMap;
    private ProgressSubscriber subscriber;
    private String upLoadUrl;


    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        getCityList();
    }

    @Override
    protected void initView() {
        rb_home = findViewById(R.id.rb_home);
        rb_loan = findViewById(R.id.rb_loan);
        rb_person = findViewById(R.id.rb_person);

        homeFragment = new HomeFragment();
        loanFragment = new LoanFragment2v();
        personFragment = new PersonalCenterFragment();


        commitFragment(R.id.main_frameLayout, homeFragment);
        mContent = homeFragment;


        checkVersion();
    }

    @Override
    protected void initEvent() {
        registrationID = JPushInterface.getRegistrationID(getApplicationContext());
//        sentJPushId(registrationID);
        super.initEvent();
        rb_home.setOnClickListener(this);
        rb_loan.setOnClickListener(this);
        rb_person.setOnClickListener(this);

    }

    private void sentJPushId(final String registrationID) {
        if (request == null) {
            request = new UserInfoRequest();
            onNextListener = new SubscriberOnNextListener<BaseRespond>() {
                @Override
                public void onNext(BaseRespond o) {
                }

                @Override
                public void onError(Throwable e) {

                }
            };
            fieldMap = new HashMap<>();
            fieldMap.put("registrationId", registrationID);
            subscriber = new ProgressSubscriber(onNextListener, this);
        }
        request.sentId(subscriber, fieldMap);

    }


    public void commitFragment(int layoutId, Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.replace(layoutId, fragment);
        transaction.commit();
    }

    /**
     * 切换tab页面
     *
     * @param fragment 要显示的fragment
     */
    public void switchContent(Fragment fragment) {
        if (mContent != fragment) {
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            if (!fragment.isAdded()) {
                transaction.hide(mContent).add(R.id.main_frameLayout, fragment)
                        .commit();
            } else {
                transaction.hide(mContent).show(fragment)
                        .commitAllowingStateLoss();
            }
            mContent = fragment;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.rb_home:
                switchContent(homeFragment);
                ImmersionBar.with(this).statusBarDarkFont(false).init();
                break;
            case R.id.rb_loan:
                switchContent(loanFragment);
                ImmersionBar.with(this).statusBarDarkFont(true,0.2f).init();
                break;
            case R.id.rb_person:
                switchContent(personFragment);
                ImmersionBar.with(this).statusBarDarkFont(true,0.2f).init();
                break;
        }
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    /**
     * 检查版本跟新
     */
    private void checkVersion() {
        checkVersionPresent = new CheckVersionPresent(mContext, this);
        checkVersionPresent.checkVersion();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {

            if (!isExit) {
                toastShortShow("请再次点击退出应用");
                isExit = true;
                currentTime = System.currentTimeMillis();
                return false;
            }

            isExit = false;

            if (System.currentTimeMillis() - currentTime <= 3000) {
                return super.onKeyDown(keyCode, event);
            } else {
                toastShortShow("请再次点击退出应用");
                return false;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public int getCurrentVersion() {

        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void onSuccess(Object object) {
        CheckVersionRespond respond = (CheckVersionRespond) object;
        if (respond.getResCode().equals("200")) {
            upLoadUrl = respond.getData().getLink();
            String latestVersion = respond.getData().getLatestVersion();
            double lastVersion = Double.parseDouble(latestVersion);
            if (lastVersion > getCurrentVersion()) {
                SpConfig.getInstance().putString(Constants.NEWVERSIONURI_STRING, respond.getData().getLink());
                if("1".equals(respond.getData().getNeedUpd())){
                    showMustUpdateDialog();
                }else{
                    showUpdateDailog();
                }
            }
        } else {
            toastShortShow(respond.getResDesc());
        }
    }

    /**
     * 强制更新
     */
    private void showMustUpdateDialog() {

        if (updateDialog == null) {

            updateDialog = new BaseDialog.Builder().layResuorce(R.layout.dialog_check_version2)
                    .okViewClickEvent(R.id.tv_one_btn)
                    .animResource(R.style.dialog_animation_fade)
                    .outSideCancel(false)
                    .gravityStyle(Gravity.CENTER)
                    .dialogWidth(-2)
                    .build();

            updateDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    updateDialog.dismiss();
                    Intent service = new Intent(mContext, DownLoadService.class);
                    Logger.d("apkUploadUrl = " + upLoadUrl);
                    service.putExtra(Constants.APKUPLOAD_URL_STRING, upLoadUrl);
                    startService(service);
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        updateDialog.show(getSupportFragmentManager(), TAG);
    }


    private void showUpdateDailog() {

        if (updateDialog == null) {

            updateDialog = new BaseDialog.Builder().layResuorce(R.layout.dialog_check_version)
                    .okViewClickEvent(R.id.tv_update)
                    .cancelViewClickEvent(R.id.tv_cancel)
                    .animResource(R.style.dialog_animation_fade)
                    .outSideCancel(false)
                    .gravityStyle(Gravity.CENTER)
                    .dialogWidth(-2)
                    .build();

            updateDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    updateDialog.dismiss();
                    Intent service = new Intent(mContext, DownLoadService.class);
                    Logger.d("apkUploadUrl = " + upLoadUrl);
                    service.putExtra(Constants.APKUPLOAD_URL_STRING, upLoadUrl);
                    startService(service);
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        updateDialog.show(getSupportFragmentManager(), TAG);
    }

    @Override
    public void onError(Throwable e) {

    }

    private void getCityList() {
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<CityListRespon>() {
            @Override
            public void onNext(CityListRespon subjects) {
                IOUtil.saveObject(mContext, Constants.CITYLIST, subjects);
            }

            @Override
            public void onError(Throwable e) {

            }
        };

        HashMap<String, Object> fieldsMap = new HashMap<>();
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.getAreaDate(new ProgressSubscriber(onNextListener, mContext), fieldsMap);
    }


}
